React-Native项目在Android真机上调试

页面路由 解决方案

路由插件:React Navigation

微信支付 解决方案

微信插件:react-native-wechat

参考文档
APP端开发步骤
react-native-wechat微信组件的使用
react-native-wechat (react-native 微信分享、支付)

图片上传 解决方案

图片插件:react-native-image-crop-picker 支持从相机和图库选择图片,裁剪图片,返回base64格式

参考文档
react-native-image-crop-picker 配置教程

WebView 解决方案

react native 原生库移除了webview组件,故用第三方库react-native-webview,API跟官方文档的一模一样

1. 高度自适应

商品详情页要展示后台返回的一段html,需要给定webview一个高度,但是又不能写成固定高度,所以需要获取内容的高度,达到自适应。

解决方案

使用injectedJavaScript注入一段js代码获取网页内容高度,然后调用window.postMessage方法把高度回调给onMessage方法,然后setState,改变webview高度,从而实现自适应。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//injectedJavaScript 注入的代码
const BaseScript =
`
(function () {
var height = null;
function changeHeight() {
if (document.body.scrollHeight != height) {
height = document.body.scrollHeight;
if (window.postMessage) {
window.postMessage(JSON.stringify({
type: 'setHeight',
height: height,
}))
}
}
}
setTimeout(changeHeight, 300);
} ())
`
1
2
3
4
5
6
7
8
9
10
11
// web端发送过来的交互消息
onMessage(event) {
try {
const action = JSON.parse(event.nativeEvent.data)
if (action.type === 'setHeight' && action.height > 0) {
this.setState({ height: action.height })
}
} catch (error) {
// pass
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// webview 配置
<WebView
injectedJavaScript={BaseScript}
style={{
width: Dimensions.get('window').width,
height: this.state.height
}}
automaticallyAdjustContentInsets
source={{ html: html }}// 后台返回的html
decelerationRate='normal'
javaScriptEnabled //仅限Android平台。iOS平台JavaScript是默认开启的。
domStorageEnabled // 适用于安卓,开启DOM本地存储
scrollEnabled={false} //不启动滑动
onMessage={this.onMessage.bind(this)}
/>

2. iOS缩放问题

ios的webview有两种:UIWebView和WKWebView,旧的UIWebView可以通过设置scalesPageToFit来自动适配视图,但是真机体验中有内存泄露问题,造成闪退,抛弃之。新的WKWebView不会自动适配,故要自己设置。

解决方案

把后台返回的html代码组装成设置了宽度自适应的完整html即可

1
2
3
4
5
6
const html = '<!DOCTYPE html><html lang="en"><head>'
+ '<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">'
+ '<title>test</title></head>'
+ '<body>'
+ this.state.html //后台返回的html
+ '</body></html>'

热更新 解决方案

热更新插件:react-native-pushy

重要API 作用
isFirstTime 是否更新后的首次启动
markSuccess 确保更新成功
checkUpdate 检查更新
downloadUpdate 下载更新版本
switchVersion 立即重启应用

1.热更新之后图片丢失

解决方案:把图片重新压缩一次 TinyPNG

参考文档
react-native-pushy教程

一些报错的解决方法

1.连接不上真机

1
2
Execution failed for task ':app:installDebug'  
Failed to install on any devices.

解决方法:下载一个ADB工具包,运行adb devices命令即可。

2.安卓依赖出错

在开发过程中会尝试很多插件,有时候删除不干净或冲突之后,项目经常会跑不起来,有各种各样的报错。

1
Execution failed for task ':app:processDebugResources'

解决方法:在android目录下运行gradlew clean命令,清理已构建的项目以及依赖,再重新运行项目即可。